/**
 * 
 */
package com.czmh.etc.onlinepubsys.services.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czmh.etc.common.core.utils.JwtUtil;
import com.czmh.etc.common.core.utils.Sequence;
import com.czmh.etc.onlinepubsys.constants.RedisKey;
import com.czmh.etc.onlinepubsys.entity.mingchuang.EtcOrder;
import com.czmh.etc.onlinepubsys.exceptions.EtcMsgException;
import com.czmh.etc.onlinepubsys.feign.newrun.SsoClient;
import com.czmh.etc.onlinepubsys.json.JsonResult;
import com.czmh.etc.onlinepubsys.maper.EtcUserMapper;
import com.czmh.etc.onlinepubsys.maper.EtcWechatauthorizedMapper;
import com.czmh.etc.onlinepubsys.maper.mingchuang.MingchuangOrderMapper;
import com.czmh.etc.onlinepubsys.model.EtcUser;
import com.czmh.etc.onlinepubsys.model.EtcWechatauthorized;
import com.czmh.etc.onlinepubsys.services.EtcUserInfoSevice;
import com.czmh.etc.onlinepubsys.services.ISsoService;
import com.czmh.etc.onlinepubsys.utils.JsonResultUtil;
import com.czmh.etc.onlinepubsys.utils.MD5Utils;
import com.czmh.etc.onlinepubsys.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @描述： 
 * @author： Seven.
 * @创建日期：Oct 22, 2019 1:51:13 PM. 
 * @版本：1.0.0
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class SsoServiceImpl implements ISsoService {
    @Autowired
    private EtcUserInfoSevice         etcUserInfoSevice;
    @Autowired
    private WxMpService               wxMpService;
    @Autowired
    private SsoClient                 ssoClient;
    @Autowired
    private RedisUtil                 redisUtil;
    @Autowired
    private EtcWechatauthorizedMapper etcWechatauthorizedMapper;
    @Autowired
    private EtcUserMapper             etcUserMapper;

    @Autowired
    private MingchuangOrderMapper mingchuangOrderMapper;

    @Override
    public JsonResult checkPassword(String mobile) throws EtcMsgException {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = new HashMap<String, Object>(0);
        params.put("user_phone", mobile);
        EtcUser etcUser = etcUserMapper.getAll(params).isEmpty() ? null : etcUserMapper.getAll(params).get(0);
        if (etcUser == null) {
            result.put("status", 2);

        } else {
            if(null == etcUser.getUser_loginpass()){
                result.put("status", 0);
            }else{
                result.put("status", 1);
            }
        }
        return JsonResultUtil.toResult(result);
    }

    /**
     * 通过手机号码和密码登陆
     * @param mobile        手机号
     * @param password        密码
     * @return
     */
    @Override
    public JsonResult changePassword(String mobile, String password) {
        EtcUser etcUser = etcUserInfoSevice.queryUserByMobile(mobile);
        if (etcUser == null){
            return JsonResultUtil.toErrorResult("用户不存在");
        }
        String md5Lower = "";
        try {
            md5Lower = MD5Utils.getMD5Lower(password);
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage());
            e.printStackTrace();
            return JsonResultUtil.toErrorResult("密码更新失败");
        }
        etcUser.setUser_loginpass(md5Lower);
        etcUserMapper.update(etcUser);
        return JsonResultUtil.toResult();
    }

    /**
     * 通过手机号码和密码登陆
     * @param mobile        手机号
     * @param password        密码
     * @return
     */
    @Override
    public JsonResult loginByPassword(String mobile, String password) {
        EtcUser etcUser = etcUserInfoSevice.queryUserByMobile(mobile);
        if (etcUser == null){
            return JsonResultUtil.toErrorResult("用户不存在");
        }
        String md5Lower = "";
        try {
            md5Lower = MD5Utils.getMD5Lower(password);
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        //判断用户密码是否存在，如果用户密码不存在且使用密码登陆的话统一返回密码错误提示
        if(etcUser.getUser_loginpass() != null && md5Lower.equalsIgnoreCase(etcUser.getUser_loginpass().toLowerCase())){
            Map<String, String> map = new HashMap<>();
            map.put("id", etcUser.getUser_id());
            map.put("loginName", etcUser.getUser_phone());
            map.put("mobile", etcUser.getUser_phone());
            map.put("createTime", "");
            map.put("updateTime", "");
            map.put("loginName", etcUser.getUser_loginname());
            map.put("loginPass", etcUser.getUser_loginpass());
            map.put("openid", etcUser.getOpenid());
            map.put("headimgurl", etcUser.getUser_headimg());
            map.put("loginName", etcUser.getUser_loginname());
            // 生成用户token
            String token = JwtUtil.createToken(etcUser.getUser_id());
            map.put("token", token);
            Map<String, String> loginInfoMap = new HashMap<>();
            loginInfoMap.put("etcUserInfo", JSONObject.toJSONString(etcUser));
            redisUtil.set(RedisKey.APP_TOKEN + token, JSON.toJSONString(loginInfoMap), 1728000);
            redisUtil.set(RedisKey.LONGIN_ONLY_KEY+mobile, token, 1728000);
            // 使用用户系统用户id作为key存储纽润的用户id值，以便在后续中请求纽润的接口中使用到
            return JsonResultUtil.toResult(map);
        }else{
            return JsonResultUtil.toErrorResult("密码错误");
        }
    }


    @Override
    public JsonResult loginByMobile(String mobile) {
        EtcUser etcUser = etcUserInfoSevice.loginByMobile(mobile);
        Map<String, String> map = new HashMap<>();
        map.put("id", etcUser.getUser_id());
        map.put("loginName", etcUser.getUser_phone());
        map.put("mobile", etcUser.getUser_phone());
        map.put("createTime", "");
        map.put("updateTime", "");
        map.put("loginName", etcUser.getUser_loginname());
        map.put("loginPass", etcUser.getUser_loginpass());
        map.put("openid", etcUser.getOpenid());
        map.put("headimgurl", etcUser.getUser_headimg());
        map.put("loginName", etcUser.getUser_loginname());
//        JsonResult jsonResult = ssoClient.login(mobile, "17");
//        log.info("登录返回信息：" + JSON.toJSONString(jsonResult));
//        if (!JsonResult.CODE_SUCCESS.equals(jsonResult.getCode().toString())) {
//            throw new EtcMsgException(jsonResult.getCode(), jsonResult.getMessage());
//        } else {
//            if (jsonResult.getData() != null) {
//                Map<String, Object> resultMap = JsonResultUtil.beanToMap(jsonResult);
//                Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("data");
                // 生成用户token
                String token = JwtUtil.createToken(etcUser.getUser_id());
//                String token = dataMap.get("token").toString();
//                String id = dataMap.get("id").toString();
                map.put("token", token);
                Map<String, String> loginInfoMap = new HashMap<>();
                loginInfoMap.put("etcUserInfo", JSONObject.toJSONString(etcUser));
                redisUtil.set(RedisKey.APP_TOKEN + token, JSON.toJSONString(loginInfoMap), 1728000);
                redisUtil.set(RedisKey.LONGIN_ONLY_KEY+mobile, token, 1728000);
                // 使用用户系统用户id作为key存储纽润的用户id值，以便在后续中请求纽润的接口中使用到
//                redisUtil.set(etcUser.getUser_id(), id, 1728000);
                return JsonResultUtil.toResult(map);
//            } else {
//                throw new EtcMsgException(jsonResult.getCode(), jsonResult.getMessage());
//            }
//        }
    }

    @Override
    public JsonResult loginAuthWx(String code) throws Exception {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
        String openid = wxMpUser.getOpenId();
        String tx = wxMpUser.getHeadImgUrl();
        String unionid = wxMpUser.getUnionId();
        String name = wxMpUser.getNickname();
        // 保存用户授权信息
        EtcWechatauthorized wechatauthorized = new EtcWechatauthorized(Sequence.getId());
        wechatauthorized.setCity(wxMpUser.getCity());
        wechatauthorized.setCountry(wxMpUser.getCountry());
        wechatauthorized.setCreatetime(new Date());
        wechatauthorized.setHeadimgurl(wxMpUser.getHeadImgUrl());
        wechatauthorized.setNickname(name);
        wechatauthorized.setOpenid(openid);
        wechatauthorized.setProvince(wxMpUser.getProvince());
        wechatauthorized.setRefreshtime(new Date());
        wechatauthorized.setSex(wxMpUser.getSex());
        wechatauthorized.setUnionid(unionid);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("unionid", unionid);
        List<EtcWechatauthorized> all = etcWechatauthorizedMapper.getAll(params);
        if (all.isEmpty()) {
            wechatauthorized.setAuthorizedid(Sequence.getId());
            etcWechatauthorizedMapper.insert(wechatauthorized);
        } else {
            EtcWechatauthorized wechatauthorized2 = all.get(0);
            wechatauthorized.setAuthorizedid(wechatauthorized2.getAuthorizedid());
            etcWechatauthorizedMapper.update(wechatauthorized);
        }
        
        Map<String, String> map = new HashMap<>();
        map.put("openid", openid);
        map.put("nickname", name);
        map.put("headimgurl", tx);
        map.put("unionid", unionid);
        map.put("mobile", "");
        // 查询该用户是否已注册
        params.clear();
        params.put("openid", openid);
        EtcUser etcUser = etcUserMapper.getByUnionid(unionid);
        if (etcUser != null && StringUtils.isNotEmpty(etcUser.getUser_phone())) {
            return this.loginByMobile(etcUser.getUser_phone());
        } else {
            return JsonResultUtil.toResult(map);
        }
    }

    @Override
    public JsonResult outlogin(String mobile) {
        return JsonResultUtil.toResult();
    }

    @Override
    public JsonResult checkVip(String phone) {
        JsonResult result = JsonResultUtil.toResult();
        EtcUser etcUser = etcUserInfoSevice.queryUserByMobile(phone);
        if(null == etcUser){
            result.setStatus(false);
            result.setMessage("非VIP");
            return result;
        }
        QueryWrapper<EtcOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", etcUser.getUser_id());
        wrapper.eq("payState", 1);
        Integer count = mingchuangOrderMapper.selectCount(wrapper);
        if (count > 0) {
            result.setStatus(true);
            result.setMessage("是VIP");
        } else {
            result.setStatus(false);
            result.setMessage("非VIP");
        }
        return result;
    }

    @Override
    public JsonResult loginByApplet(String userinfo) {
        JSONObject userInfoJSON = JSONObject.parseObject(userinfo);
        // 保存用户信息
        EtcUser etcUser = etcUserInfoSevice.saveUserInfo(userInfoJSON);
        Map<String, String> map = new HashMap<>();
        String openId = userInfoJSON.get("openId") == null ? "" : userInfoJSON.get("openId").toString();
        String unionId = userInfoJSON.get("unionId") == null ? "" : userInfoJSON.get("unionId").toString();
        String nickname = userInfoJSON.get("nickName").toString();
        String headimgurl = userInfoJSON.get("avatarUrl").toString();
        map.put("openid", openId);
        map.put("nickname", nickname);
        map.put("headimgurl", headimgurl);
        map.put("unionid", unionId);
        map.put("mobile", "");
        if (StringUtils.isNotEmpty(etcUser.getUser_phone())) {
            return this.loginByMobile(etcUser.getUser_phone());
        } else {
            return JsonResultUtil.toResult(map);
        }
    }

}
